package main

import (
	"GOPAAS/configs/config"
	"GOPAAS/internal/app/database"
	router "GOPAAS/internal/app/routers"
	"flag"
	"fmt"
	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/flow"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"io"
	"log"
	"os"
	"strconv"
	"time"
)

func init() {
	env := *flag.String("e", "dev", "当前运行环境")
	flag.Parse()
	//env := os.Getenv("FFENV", "dev") //当前环境
	if env != "dev" && env != "prod" {
		env = "dev"
	}
	fmt.Println("当前运行环境：" + env)
	path, _ := os.Executable()
	fmt.Println("当前目录：" + path)
	//初始化配置
	conf := config.ConfInit(env)
	var gin_env = "debug"
	if env == "prod" {
		gin_env = "release"
	}
	gin.SetMode(gin_env)
	database.InitDriver(conf.Database)
}

func main() {
	InitLog()      //初始化日志
	InitCron()     //初始化定时任务
	InitSentinel() //初始化限流配置
	r := router.NewRouter()
	r.Run(":" + strconv.Itoa(config.Conf.Port))
}
func InitLog() {
	logPath := "./logs"
	//logrus.SetReportCaller(true)
	logrus.SetFormatter(&logrus.TextFormatter{})
	//writer1 := &bytes.Buffer{}
	dir_name := strconv.Itoa(time.Now().Year()) + strconv.Itoa(int(time.Now().Month()))
	dir_path := logPath + "/" + dir_name
	if _, path_err := os.Stat(dir_path); os.IsNotExist(path_err) {
		os.MkdirAll(dir_path, 0777)
	}
	file_name := strconv.Itoa(time.Now().Year()) + fmt.Sprintf("%02d", int(time.Now().Month())) + fmt.Sprintf("%02d", time.Now().Day()) + ".log"
	file_path := dir_path + "/" + file_name
	writer2 := os.Stdout
	if _, path_err := os.Stat(file_path); os.IsNotExist(path_err) {
		os.Create(file_path)
	}
	writer3, err := os.OpenFile(file_path, os.O_WRONLY|os.O_APPEND, 0755)
	if err != nil {
		log.Fatalf("create file logs failed: %v", err)
	}
	logrus.SetOutput(io.MultiWriter(writer2, writer3))
}

func InitSentinel() {
	//基于sentinel的qps限流
	//必须初始化
	err := sentinel.InitDefault()
	if err != nil {
		logrus.Fatalf("Unexpected error: %+v", err)
	}

	//配置限流规则：1秒内通过10次
	_, err = flow.LoadRules([]*flow.Rule{
		{
			Resource:               "api_request",
			TokenCalculateStrategy: flow.Direct,
			ControlBehavior:        flow.Reject, //超过直接拒绝
			Threshold:              50,          //请求次数
			StatIntervalInMs:       1000,        //允许时间内
		},
	})

	if err != nil {
		logrus.Fatalf("Unexpected error: %+v", err)
		return
	}
}
